package com.fcy.teamwork.business.main.homepage

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.fcy.teamwork.App
import com.fcy.teamwork.base.BaseActivity
import com.fcy.teamwork.base.BaseFragment
import com.fcy.teamwork.base.toActivity
import com.fcy.teamwork.base.toJson
import com.fcy.teamwork.bean.Task
import com.fcy.teamwork.bean.User
import com.fcy.teamwork.bean.generateTaskList
import com.fcy.teamwork.business.checkapply.CheckApplyActivity
import com.fcy.teamwork.business.main.homepage.adapter.ProjectsEntranceAdapter
import com.fcy.teamwork.business.main.homepage.viewmodel.MineVM
import com.fcy.teamwork.business.newproject.NewProjectActivity
import com.fcy.teamwork.business.projectlife.ProjectControllerAct
import com.fcy.teamwork.databinding.HomepageMineBinding
import kotlinx.coroutines.launch

class MineFrag : BaseFragment<HomepageMineBinding>() {
    private val vm: MineVM by activityViewModels()
    private val adapter = ProjectsEntranceAdapter().apply {
        onItemClickAction = { it ->
            val intent = Intent(this@MineFrag.requireContext(), ProjectControllerAct::class.java)
            intent.putExtra("projectInfo", it.toJson())
            startActivity(intent)
        }
    }

    override fun initViewBinding(
        inflater: LayoutInflater?,
        container: ViewGroup?
    ) = HomepageMineBinding.inflate(layoutInflater)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.actionBar.apply {
            tvTitle.text = "我的"
            if (App.person.clazz == null) {
                newProject.visibility = View.VISIBLE
                newProject.setOnClickListener {
                    val intent = Intent(requireContext(), NewProjectActivity::class.java)
                    startActivity(intent)
                }
            }
        }
        binding.rvAllThings.also {
            it.layoutManager = LinearLayoutManager(this@MineFrag.context)
            it.adapter = adapter
        }
        binding.processApply.root.setOnClickListener {
            Intent(context, CheckApplyActivity::class.java).apply {
                startActivity(this)
            }
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                adapter.submitData(
                    vm.loadMineProjects()
                )
            }
        }
    }
}